package com.tmc.util;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

public class XMLBeanUtil {
	
	 //Create the desired XmlObject and provide it as the test object
    public static org.apache.xmlbeans.XmlObject getTestObject(java.lang.Class type)
        throws java.lang.Exception {
        java.lang.reflect.Method creatorMethod = null;

        if (org.apache.xmlbeans.XmlObject.class.isAssignableFrom(type)) {
            Class[] declaredClasses = type.getDeclaredClasses();

            for (int i = 0; i < declaredClasses.length; i++) {
                Class declaredClass = declaredClasses[i];

                if (declaredClass.getName().endsWith("$Factory")) {
                    creatorMethod = declaredClass.getMethod("newInstance", null);

                    break;
                }
            }
        }

        if (creatorMethod != null) {
            return (org.apache.xmlbeans.XmlObject) creatorMethod.invoke(null,
                null);
        } else {
            throw new java.lang.Exception("Creator not found!");
        }
    }
    
    /** 
     * 将对象直接转换成String类型�? XML输出 
     * @param obj 
     * @return 
     */  
    public static String convertToXml(Object obj) {  
        // 创建输出�?  
        StringWriter sw = new StringWriter();  
        try {  
            // 利用jdk中自带的转换类实�?  
            JAXBContext context = JAXBContext.newInstance(obj.getClass());  
  
            Marshaller marshaller = context.createMarshaller();  
            // 格式化xml输出的格�?  
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,  
                    Boolean.TRUE);  
            // 将对象转换成输出流形式的xml  
            marshaller.marshal(obj, sw);  
        } catch (JAXBException e) {  
            e.printStackTrace();  
        }  
        return sw.toString();  
    } 
    
    /** 
     * 将对象根据路径转换成xml文件 
     * @param obj 
     * @param path 
     * @return 
     */  
    public static void convertToXml(Object obj, String path) {  
        try {  
            // 利用jdk中自带的转换类实�?  
            JAXBContext context = JAXBContext.newInstance(obj.getClass());  
  
            Marshaller marshaller = context.createMarshaller();  
            // 格式化xml输出的格�?  
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,  
                    Boolean.TRUE);  
            // 将对象转换成输出流形式的xml  
            // 创建输出�?  
            FileWriter fw = null;  
            try {  
                fw = new FileWriter(path);  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            marshaller.marshal(obj, fw);  
        } catch (JAXBException e) {  
            e.printStackTrace();  
        }  
    } 
    
    public static Object convertXmlStrToObject1(Class clazz,String elementName,String xmlStr){
    	Object xmlObject = null;  
        try {
        	Document document = DocumentHelper.parseText(xmlStr); 
        	//如果不是SOAP返回的报文，是XML字符串则不需要这行代码 
            String beanXml = document.getRootElement().element(elementName).asXML();
            JAXBContext context = JAXBContext.newInstance(clazz);  
            // 进行将Xml转成对象的核心接口  
            Unmarshaller unmarshaller = context.createUnmarshaller();  
            StringReader sr = new StringReader(beanXml);  
            xmlObject = unmarshaller.unmarshal(sr);  
        } catch (JAXBException e) {  
            e.printStackTrace();  
        } catch (DocumentException e) {
			e.printStackTrace();
		}  
        return xmlObject;  
    }
    
    @SuppressWarnings("unchecked")  
    /** 
     * 将String类型的xml转换成对�? 
     */  
    public static Object convertXmlStrToObject(Class clazz,String elementName,String xmlStr) {  
        Object xmlObject = null;  
        try {
        	Document document = DocumentHelper.parseText(xmlStr); 
        	//如果不是SOAP返回的报文，是XML字符串则不需要这行代�?  
            String beanXml = document.getRootElement().element("Body").element(elementName).asXML();
            JAXBContext context = JAXBContext.newInstance(clazz);  
            // 进行将Xml转成对象的核心接�?  
            Unmarshaller unmarshaller = context.createUnmarshaller();  
            StringReader sr = new StringReader(beanXml);  
            xmlObject = unmarshaller.unmarshal(sr);  
        } catch (JAXBException e) {  
            e.printStackTrace();  
        } catch (DocumentException e) {
			e.printStackTrace();
		}  
        return xmlObject;  
    } 
    
    @SuppressWarnings("unchecked")  
    /** 
     * 将file类型的xml转换成对�? 
     */  
    public static Object convertXmlFileToObject(Class clazz, String xmlPath) {  
        Object xmlObject = null;  
        try {  
            JAXBContext context = JAXBContext.newInstance(clazz);  
            Unmarshaller unmarshaller = context.createUnmarshaller();  
            FileReader fr = null;  
            try {  
                fr = new FileReader(xmlPath);  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            }  
            xmlObject = unmarshaller.unmarshal(fr);  
        } catch (JAXBException e) {  
            e.printStackTrace();  
        }  
        return xmlObject;  
    }

}
